<template>
  <view class="home u-flex-col">
    <u-navbar
      class="nav"
      title="筛选"
      :title-bold="true"
      back-icon-color="#333333"
      title-color="#000"
    ></u-navbar>
    <view class="u-p-20 form">
      <u-form :model="form" ref="uForm">
        <u-form-item
          :border-bottom="false"
          :label-style="labelStyle"
          prop="sensorType"
          label-position="top"
          label="传感器类型"
        >
          <u-input
            v-model="form.sensorName"
            :placeholder-style="placeholderStyle"
            :custom-style="inputStyle"
            type="select"
            placeholder="请选择传感器类型"
            @click="openSensor"
          />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          :label-style="labelStyle"
          label-position="top"
          label="时间"
        >
          <div class="time-body">
            <uni-datetime-picker :border="false" placeholder="请选择开始时间" return-type="timestamp" v-model="form.beginDate" />
          </div>
        </u-form-item>
        <u-form-item :border-bottom="false" label-position="top">
          <div class="time-body">
            <uni-datetime-picker :border="false" placeholder="请选择结束时间" return-type="timestamp" v-model="form.endDate" />
          </div>
        </u-form-item>
      </u-form>
    </view>
    <view class="confrim-btn u-flex u-row-between u-p-t-20">
      <u-button
        :hair-line="false"
        shape="circle"
        form-type="reset"
        :custom-style="formCustomStyle"
        throttle-time="500"
        @click="reset"
        >重置</u-button
      >
      <u-button
        :hair-line="false"
        shape="circle"
        :custom-style="formSubmitStyle"
        form-type="submit"
        throttle-time="500"
        @click="submit"
        >确定</u-button
      >
    </view>
    <u-popup mode="bottom" v-model="show">
      <view class="popup-content">
        <view class="u-flex u-row-between u-p-b-30">
          <u-button
            :hair-line="false"
            :custom-style="customStyle"
            throttle-time="500"
            @click="cancelSensor"
            >取消</u-button
          >
          <u-button
            :hair-line="false"
            :custom-style="submitStyle"
            throttle-time="500"
            @click="clickSensor"
            >确定</u-button
          >
        </view>
        <view class="u-p-b-20">
          <u-search
            placeholder="请输入传感器类型"
            v-model="filtersensorTypesVal"
            shape="square"
            bg-color="#E5EAE8"
            height="80"
            :show-action="true"
            :animation="true"
            :input-style="{ marginLeft: '20rpx' }"
            :search-icon="searchSrc"
            placeholder-color="#999999"
            :action-style="{
              color: '#369164',
              fontSize: '14px',
              fontWeight: '400',
            }"
          ></u-search>
        </view>
        <scroll-view scroll-y="true" style="height: 600rpx">
          <view class="w-100p checkbox">
            <u-checkbox-group active-color="#9AC8B1" width="100%" :wrap="true">
              <u-checkbox
                @change="checkboxsensorTypesChange"
                v-model="item.checked"
                class="checkbox-item"
                v-for="(item, index) in filtersensorTypesList"
                :key="index"
                :name="item.name"
                >{{ item.name }}</u-checkbox
              >
            </u-checkbox-group>
            <template v-if="filtersensorTypesList.length === 0">
              <view class="c-empty p-absolute-center">
                <u-empty text="暂无数据"></u-empty>
              </view>
            </template>
          </view>
        </scroll-view>
      </view>
    </u-popup>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  name: "screen",
  data() {
    return {
      show: false,
      showTimeStart: false,
      showTimeEnd: false,
      customerCode: "", //煤矿编码
      cdCode: "", //测点编码
      arr: [],
      arrTwo: [],
      data:{},
      form: {
        sensorType: [], // 传感器类型
        sensorName: "", // 传感器类型名称
        beginDate:"", //开始时间
        endDate: "", // 结束时间
      },
      sensorType: [], // 传感器类型
      sensorName: "", // 传感器类型名称
      filtersensorTypesVal: "", //传感器类型搜索数据
      sensorTypesList: [],
      rules: {
      },
      labelStyle: {
        color: "#333333",
        fontWeight: "600",
      },
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true,
        timestamp: true,
      },
      searchData: {
        name: "",
      },
      inputStyle: {
        background: "#F1F5F3",
        paddingLeft: "20rpx",
        color: "#999999",
        borderRadius: "20rpx",
      },
      placeholderStyle: "color:#999999;",
      searchSrc: require("@/static/image/search_icon.svg"),
      formCustomStyle: {
        color: "#333333",
        background: "#F1F5F3",
        width: "40%",
        border: "none",
      },
      formSubmitStyle: {
        color: "#333333",
        background: "#5BAC84",
        width: "40%",
        border: "none",
      },
      customStyle: {
        // 注意驼峰命名，并且值必须用引号包括，因为这是对象
        color: "#333333",
        background: "#F1F5F3",
        borderRadius: "20rpx",
        width: "40%",
        border: "none",
      },
      submitStyle: {
        color: "#333333",
        background: "#5BAC84",
        borderRadius: "20rpx",
        width: "40%",
        border: "none",
      },
      parentSensorType:'', //初始值，用于重置
      parentStart:'',//初始开始时间，用于重置
      parentEnd:''//初始值结束时间，用于重置
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  computed: {
    filtersensorTypesList() {
      return this.sensorTypesList.filter((item) => {
        return this.filtersensorTypesVal
          ? item.name?.indexOf(this.filtersensorTypesVal) >= 0 ||
              item.pinyin_code?.indexOf(
                this.filtersensorTypesVal.toUpperCase()
              ) >= 0
          : true;
      });
    },
  },
  async mounted() {
    await this.getSensorTypeDictList();
    this.getSensorName(this.data.sensorType)
    this.initSensor()
  },
  methods: {
    openSensor() {
      this.show = true;
    },
    // 传感器类型数据初始化
    initSensor() {
      if (this.form.sensorName !== "") {
        this.arr = [];
        this.arrTwo = [];
        for (let i = 0; i < this.sensorTypesList.length; i++) {
          if (
            this.form.sensorName.indexOf(this.sensorTypesList[i].sensorName) !==
            -1
          ) {
            this.arr.push(this.sensorTypesList[i].sensorName);
            this.arrTwo.push(this.sensorTypesList[i].sensorType);
            this.$set(this.sensorTypesList[i], "checked", true);
          } else {
            this.$set(this.sensorTypesList[i], "checked", false);
          }
        }
        this.$set(this, "sensorType", this.arrTwo);
        this.$set(this, "sensorName", this.arr.toString());
      } else {
        this.arr = [];
        this.arrTwo = [];
        for (let i = 0; i < this.sensorTypesList.length; i++) {
          this.$set(this.sensorTypesList[i], "disabled", false);
          this.$set(this.sensorTypesList[i], "checked", false);
        }
        this.$set(this, "sensorType", []);
        this.$set(this, "sensorName", "");
      }
    },
    // 传感器类型数据取消
    cancelSensor() {
      this.initSensor();
      this.show = false;
      this.filtersensorTypesVal = "";
    },
    // 传感器类型数据确认
    clickSensor() {
      this.$set(this.form, "sensorType", this.sensorType);
      this.$set(this.form, "sensorName", this.sensorName);
      this.filtersensorTypesVal = "";
      this.show = false;
    },
    // 选中sensorType某个复选框时，由checkbox时触发
    checkboxsensorTypesChange(e) {
      if (e.value === true) {
        this.arr.push(e.name);
        for (let i = 0; i < this.sensorTypesList.length; i++) {
          if (this.sensorTypesList[i].sensorName === e.name) {
            this.arrTwo.push(this.sensorTypesList[i].sensorType);
          }
        }
      } else {
        this.deleteOne(e.name, this.arr);
        for (let i = 0; i < this.sensorTypesList.length; i++) {
          if (this.sensorTypesList[i].sensorName === e.name) {
            this.deleteOne(this.sensorTypesList[i].sensorType, this.arrTwo);
          }
        }
      }
      this.sensorType = this.arrTwo;
      this.sensorName = this.arr.toString();
    },
    deleteOne(str, arr) {
      let index = arr.indexOf(str);
      arr.splice(index, 1);
      return arr;
    },
    //获取传感器类型及报警类型列表
    async getSensorTypeDictList() {
      let params = {
        customerNo: this.customerCode, //煤矿编码
        cdCode: this.cdCode, //测点编码
      };
      const res = await this.$form("/alarm/fusionAnalysis/getSensorTypeList", params);
      if (res && res.body) {
        this.sensorTypesList = res.body;
        for (let i = 0; i < this.sensorTypesList.length; i++) {
          this.$set(this.sensorTypesList[i], "disabled", false);
          this.$set(this.sensorTypesList[i], "checked", false);
          this.$set(
            this.sensorTypesList[i],
            "name",
            this.sensorTypesList[i].sensorName
          );
        }
      }
    },
    handlePickerConfirm(res) {
      this.form.beginDate = res.year + '-' + res.month + '-' + res.day + ' ' + res.hour + ':' + res.minute + ':' + res.second
      this.verification()
    },
    handlePickerConfirmTwo(res) {
      this.form.endDate = res.year + '-' + res.month + '-' + res.day + ' ' + res.hour + ':' + res.minute + ':' + res.second 
      this.verification()
    },
    verification(){
      let isSubmit = false
      const date = new Date(this.form.endDate)
      const dateStart = new Date(this.form.beginDate)
      if(date && dateStart && dateStart.getTime() > date.getTime()){
        this.$refs.uToast.show({
          title: '结束时间必须大于开始时间',
          type: 'error',
        })
        isSubmit = false
      } else {
        isSubmit = true
      }
      return isSubmit
    },
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if(this.verification()){
            const params = {
              ...this.form,
              beginDate: this.form.beginDate ? this.$date(this.form.beginDate): '',
              endDate: this.form.endDate ? this.$date(this.form.endDate): ''
            }
            uni.$emit("handClickCurveScreen",params);
            uni.navigateBack({
              delta: 1,
            });
          }else{
            return;
          }
        } else {
        }
      });
    },
    reset() {
      this.form = {
        sensorName: "", // 传感器类型名称
        sensorType: [], // 传感器类型
        beginDate: "", //开始时间
        endDate: "", // 结束时间
      },
      this.form.beginDate = this.parentStart || ''
      this.form.endDate = this.parentEnd || ''
      this.form.sensorType = this.parentSensorType.split(',')
      this.getSensorName(this.form.sensorType)
      this.filtersensorTypesVal = ''
      this.initSensor()
      // uni.$emit("handClickCurveScreen",this.form);
      this.$refs.uForm.resetFields(this.rules);
    },
    getSensorName(type){
      let arr = []
      for(let i = 0; i< this.sensorTypesList.length; i++){
        if(type.includes(this.sensorTypesList[i].sensorType)){
          arr.push(this.sensorTypesList[i].sensorName)
        }
      }
      this.form.sensorName = arr.toString()
    }
  },
  onLoad(options) {
    const { customerCode, cdCode ,sensorType, begin, end, data } = options;
    this.data = JSON.parse(data);
    this.parentSensorType = sensorType
    this.parentStart = begin
    this.parentEnd = end
    this.form.beginDate = this.data.startTime + ''
    this.form.endDate = this.data.endTime + ''
    this.form.sensorType = this.data.sensorType.split(',')
    this.customerCode = customerCode;
    this.cdCode = cdCode;
  },
};
</script>

<style lang="scss" scoped>
.home {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  .form {
    z-index: 999;
    box-shadow: 0px -3px 3px #f5f5f5;
    /deep/.u-input {
      .u-input__right-icon--select {
        display: none;
      }
    }
  }
  .popup-content {
    padding: 24rpx;
    text-align: center;
    .checkbox {
      &-item {
        height: 100rpx;
      }
      /deep/.u-checkbox-group {
        display: inline;
        .u-checkbox {
          border-bottom: 1px solid #dddddd;
          justify-content: space-between;
          flex-flow: row-reverse;
          .u-checkbox__icon-wrap {
            background: rgba(1, 72, 51, 0.2);
            border: none;
          }
        }
      }
    }
  }
  .confrim-btn {
    position: absolute;
    width: 100%;
    bottom: 50rpx;
  }
}

.time-body{
  position: relative;
  width: 100%;
}
</style>
